#ifndef __DEBUG__
#define __DEBUG__
#include"log.hpp"
#include<iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;

#define PATHFILE "./myfifo" //文件路径
#define MODE 0664 //权限

enum{
    FILE_CREATE_ERROR = 1,
    FILE_OPEN_ERROR,
    FILE_DEL_ERROR
};

// 共享内存的大小一般建议是4096的整数倍
// 4097,实际上操作系统给你的是4096*2的大小
const int size = 4096; 
const string pathname="/home/lyz"; //随机字符串
const int proj_id = 0x0328; //随机数字
Log log;

key_t GetKey() //获取当前的key值
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if(k < 0)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is : 0x%x", k);
    return k;
}

int GetShareMemHelper(int flag) //根据传入的flag方式，获取共享内存shmid
{
    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if(shmid < 0)
    {
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(Info, "create share memory success, shmid: %d", shmid);

    return shmid;
}

int CreateShm() //创建接口
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm() //获取接口
{
    return GetShareMemHelper(IPC_CREAT); 
}


class Init
{
public:
    Init()
    {
        int ret = mkfifo(PATHFILE, MODE);
        if(ret < 0)
        {
            //错误信息
            log(Fatal, "mkfifo error");
            exit(FILE_CREATE_ERROR); //创建文件错误
        }
    }
    ~Init() //不能解决ctrl c退出的情况
    {
        int ret = unlink(PATHFILE);
        if(ret < 0){
            log(Fatal, "unlink error");
            exit(FILE_DEL_ERROR);
        }
    }
};

#endif